﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FastReport;
using FastReport.Data;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Threading;
using 开单.ComMethod;
using 开单.Dao.基础;
using 开单.Model.基础;
using 开单.DB;


namespace 开单
{
    public partial class FrmXskd : Form
    {
        DigitToChnText CM = new DigitToChnText();
        decimal dj;
        long sl;
        XsdDao xsdDao = new XsdDao();
        XsdEntity xsdEntity = new XsdEntity();
        XsmxDao xsmxDao = new XsmxDao();
        XsmxEntity xsmxEntity = new XsmxEntity();
        KhxxDao khxxDao = new KhxxDao();
        KhxxEntity khxxEtity = new KhxxEntity();
        YgxxDao ygxxDao = new YgxxDao();
        YgxxEntity ygxxEntity = new YgxxEntity();
        HpxxDao hpxxDao = new HpxxDao();
        HpxxEntity hpxxEnity = new HpxxEntity();
        DataTable dt = new DataTable();
        DataTable dt1 = new DataTable();
        DataTable dt2 = new DataTable();
        DataTable dt3 = new DataTable();
        DataTable dtHp = new DataTable();
        private Report FReport;
        private static FrmXskd Instance;
        public FrmXskd()
        {
            InitializeComponent();
            dataGridView1.AllowUserToAddRows = false;
            uClistMoreKh.ListEvent += new ClientApplication.ComControl.UClistMore.ListEventHandler(uClistMoreKh_ListEvent);
            uClistMoreKdr.ListEvent += new ClientApplication.ComControl.UClistMore.ListEventHandler(uClistMoreKdr_ListEvent);
            uClistMoreYwy.ListEvent += new ClientApplication.ComControl.UClistMore.ListEventHandler(uClistMoreYwy_ListEvent);
            uClistMoreShr.ListEvent += new ClientApplication.ComControl.UClistMore.ListEventHandler(uClistMoreShr_ListEvent);
            ucHp.UcHpEvent += new ClientApplication.ComControl.UCHp.UcHpEventHandler(ucHp_UcHpEvent);
        }

        void ucHp_UcHpEvent(HpxxEntity hpxxEntity)
        {
            for (int i = 0; i < dataGridView1.RowCount - 1; i++)
            {
                if (dataGridView1[0, i].Value.ToString() == hpxxEntity.hp_pm)
                {
                    MessageBox.Show("该货品已在列表单中");
                    return;
                }
            }
            if (dataGridView1.Rows.Count > 0)
            {
                dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
            }
            DataGridViewRow row = new DataGridViewRow();
            row.CreateCells(dataGridView1);
            row.Cells[0].Value = (object)hpxxEntity.hp_pm;
            row.Cells[1].Value = (object)hpxxEntity.hp_gg;
            row.Cells[2].Value = (object)hpxxEntity.hp_dw;
            row.Cells[4].Value = (object)hpxxEntity.hp_dj;
            dataGridView1.Rows.Add(row);
            TotalRow(false);
        }

        public static FrmXskd GetInstance()
        {
            if (null == Instance || Instance.IsDisposed)
            {
                Instance = new FrmXskd();
                //Instance.MdiParent = GlobalVar.frmMain;
            }
            Instance.BringToFront();
            return Instance;
        }

        void uClistMoreShr_ListEvent(MyListItem myList)
        {
            TxtShr.Text = myList.TextField;
            TxtShr.Tag = myList.ValueField;
            uClistMoreShr.Visible = false;
            TxtShr.Focus();
        }

        void uClistMoreYwy_ListEvent(MyListItem myList)
        {
            TxtYwy.Text = myList.TextField;
            TxtYwy.Tag = myList.ValueField;
            uClistMoreYwy.Visible = false;
            TxtYwy.Focus();
        }

        void uClistMoreKdr_ListEvent(MyListItem myList)
        {
            TxtKdr.Text = myList.TextField;
            TxtKdr.Tag = myList.ValueField;
            uClistMoreKdr.Visible = false;
            TxtKdr.Focus();
        }

        void uClistMoreKh_ListEvent(MyListItem myList)
        {
            TxtKh.Text = myList.TextField;
            TxtKh.Tag = myList.ValueField;
            DataTable dt = khxxDao.GetKhxxDtByKhName(TxtKh.Text);
            if (dt.Rows.Count != 0)
            {
                TxtKhdh.Text = dt.Rows[0][3].ToString();
                TxtShdz.Text = dt.Rows[0][4].ToString();
                TxtYwy.Text = dt.Rows[0][2].ToString();
            }
            uClistMoreKh.Visible = false;
            TxtKh.Focus();
        }

        #region 界面事件处理
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
            }
            DataColumn column = new DataColumn();

            dataGridView1.Rows.Add(column);
            TotalRow(false);
            dataGridView1.Focus();
            //ucHp.Visible = true;
            //ucHp.textBox1.Focus();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.RowCount == 0) { return; }
            if (dataGridView1.CurrentCell.RowIndex != dataGridView1.Rows.Count - 1)
            {
                dataGridView1.Rows.RemoveAt(dataGridView1.CurrentCell.RowIndex);

                if (dataGridView1.Rows.Count == 1)
                {
                    dataGridView1.Rows.RemoveAt(0);
                }
                TotalRow(true);
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(dataGridView1[5, 0].Value.ToString());
            if (!IsOkToPrint()) { return; }
            //if (!(MessageBox.Show("确定要打印吗,选择确定将存入数据库", "提醒", MessageBoxButtons.OKCancel,
            //MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes)) { return; }
            if (MessageBox.Show("确定要保存并打印吗？", "提示", MessageBoxButtons.YesNo,
            MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) == DialogResult.No) { return; }



            DataTable dt = new DataTable();
            dt.Columns.Add("品名");
            dt.Columns.Add("规格");
            dt.Columns.Add("单位");
            dt.Columns.Add("数量");
            dt.Columns.Add("单价");

            dt.Columns.Add("合计");
            int rowNo = dataGridView1.Rows.Count;
            int columnNo = dataGridView1.ColumnCount;

            for (int i = 0; i < rowNo - 1; i++)
            {
                DataRow dr = dt.NewRow();
                for (int n = 0; n < columnNo; n++)
                {
                    dr[n] = dataGridView1[n, i].FormattedValue.ToString();
                }
                dt.Rows.Add(dr);
            }

            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            FReport = new Report();
            FReport.Load(@"xskd.frx");//加载报表路径@"C:\Program Files\xidian\invoiceprint\bin\xskd.frx"    @"invoice\xskd.frx"
            FReport.RegisterData(ds);

            Parameter kh = FReport.GetParameter("kh");
            kh.Value = TxtKh.Text;
            Parameter dh = FReport.GetParameter("dh");
            dh.Value = TxtKhdh.Text;
            Parameter kdr = FReport.GetParameter("kdr");
            kdr.Value = TxtKdr.Text;
            Parameter kdrq = FReport.GetParameter("kdrq");
            kdrq.Value = TxtKdrq.Text;
            Parameter shdz = FReport.GetParameter("shdz");
            shdz.Value = TxtShdz.Text;
            Parameter ywy = FReport.GetParameter("ywy");
            ywy.Value = TxtYwy.Text;
            Parameter shz = FReport.GetParameter("shz");
            shz.Value = TxtShr.Text;
            Parameter shsj = FReport.GetParameter("shsj");
            shsj.Value = TxtShsj.Text;
            Parameter zhj1 = FReport.GetParameter("zhj1");
            zhj1.Value = LblHj.Text;
            Parameter zhj2 = FReport.GetParameter("zhj2");
            zhj2.Value = dataGridView1[5, dataGridView1.RowCount - 1].FormattedValue.ToString();
            Parameter dhsj = FReport.GetParameter("dhsj");


            string xsd = string.Format("{0:0#00}", (xsdDao.getMaxXsdNoByMonth() + 1));//将1格式化为0001
            xsdEntity.xsd_code = "XS" + DateTime.Now.ToString("yyyyMM", CultureInfo.InvariantCulture) + xsd;
            dhsj.Value = "单据号:" + xsdEntity.xsd_code;


            SaveData();


            FReport.Design();
        }

        private void SaveData()
        {

            //xsdEntity.xsd_code = (xsdDao.getInfoCount() + 1).ToString();
            xsdEntity.xsd_khdh = TxtKhdh.Text;
            xsdEntity.xsd_kdr = TxtKdr.Text;
            xsdEntity.xsd_kh = TxtKh.Text;
            xsdEntity.xsd_ywy = TxtYwy.Text;
            xsdEntity.xsd_shr = TxtShr.Text;
            xsdEntity.xsd_shdz = TxtShdz.Text;
            xsdEntity.xsd_kdsj = TxtKdrq.Text;
            xsdEntity.xsd_shsj = TxtShsj.Text;
            xsdDao.Addxsxx(xsdEntity);
            int count = this.dataGridView1.Rows.Count;
            for (int i = 0; i < count - 1; i++)
            {
                xsmxEntity.xsmx_pm = dataGridView1[0, i].Value.ToString();
                xsmxEntity.xsmx_dj = Convert.ToDecimal(dataGridView1[4, i].Value);
                xsmxEntity.xsmx_dw = dataGridView1[2, i].Value.ToString();
                xsmxEntity.xsmx_sl = Convert.ToInt64(dataGridView1[3, i].Value);
                xsmxEntity.xsmx_gg = dataGridView1[1, i].Value.ToString();
                xsmxEntity.xsd_code = xsdEntity.xsd_code;
                xsmxDao.Addxsmx(xsmxEntity);
            }
        }

        private bool IsOkToPrint()
        {
            if (dataGridView1.RowCount == 0) { return false; }
            int rowNum = dataGridView1.RowCount;
            int colNum = dataGridView1.ColumnCount;
            //循环验证表里的数据是否正确
            for (int i = 0; i < rowNum - 1; i++)
            {
                for (int j = 0; j < colNum - 1; j++)
                {
                    if (dataGridView1[j, i].Value == null || dataGridView1[j, i].Value.ToString().Trim() == "")
                    {
                        MessageBox.Show("第" + (i + 1).ToString() + "行 第" + (j + 1).ToString() + "列未填写数据");
                        return false;
                    }
                    if (j == 3)
                    {
                        try
                        {
                            double d = Convert.ToDouble(dataGridView1[j, i].Value);
                            if (d < 0) { MessageBox.Show("第" + (i + 1).ToString() + "行数量不能小于0"); return false; }
                        }
                        catch
                        {
                            MessageBox.Show("第" + (i + 1).ToString() + "行数量不能为非数字");
                            return false;
                        }
                    }
                    if (j == 4)
                    {
                        try
                        {
                            double d = Convert.ToDouble(dataGridView1[j, i].Value);
                            if (d < 0) { MessageBox.Show("第" + (i + 1).ToString() + "行单价不能小于0"); return false; }
                        }
                        catch
                        {
                            MessageBox.Show("第" + (i + 1).ToString() + "行单价不能为非数字");
                            return false;
                        }
                    }
                }
            }
            if (TxtKh.Text.Trim() == "") { MessageBox.Show("客户未填写"); return false; }
            if (TxtKdr.Text.Trim() == "") { MessageBox.Show("开单人未填写"); return false; }
            if (TxtKdrq.Text.Trim() == "") { MessageBox.Show("开单人未填写"); return false; }
            if (TxtYwy.Text.Trim() == "") { MessageBox.Show("业务员未填写"); return false; }
            if (TxtShr.Text.Trim() == "") { MessageBox.Show("送货人未填写"); return false; }
            //if (TxtShdz.Text.Trim() == "") { MessageBox.Show("送货地址未填写"); ;return false; }
            if (TxtShsj.Text.Trim() == "") { MessageBox.Show("送货日期未填写"); return false; }
            try
            {
                DateTime dt =TxtKdrq.Value;
                if ( dt>DateTime.Now)
                {
                    MessageBox.Show("开单时间不能大于当前时间");
                    return false;
                }
                if (dt.Month < DateTime.Now.Month)
                {
                    MessageBox.Show("只允许填写当月的单据");
                    return false;
                }
            }
            catch
            {
                MessageBox.Show("请填写正确形式的开单时间");
                return false;
            }

            //try
            //{
            //    DateTime dtime = DateTime.Parse(TxtShsj.Text);
            //    dtime = DateTime.Parse(TxtKdrq.Text);
            //}
            //catch
            //{
            //    MessageBox.Show("日期格式不正确,请确认");
            //    return false;
            //}

            return true;
        }

        #endregion

        #region 编辑处理
        /// <summary>
        /// 更新合计一行
        /// </summary>
        /// <param name="lastFlag">是否删除最后一行</param>
        public void TotalRow(bool lastFlag)
        {
            //全部删除以后不用再计算合计行
            if (dataGridView1.Rows.Count < 1)
            {
                return;
            }
            double numTotal = 0;    //数量合计

            //是否要移除掉最后的合计一行
            if (lastFlag && dataGridView1.Rows.Count > 1)
            {
                dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
            }
            dataGridView1.Rows.Add();
            DataGridViewRow dgr = dataGridView1.Rows[dataGridView1.Rows.Count - 1];
            dgr.ReadOnly = true;
            dgr.DefaultCellStyle.BackColor = System.Drawing.Color.Khaki;
            dgr.Cells["Column1"].Value = "总合计";
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                numTotal = numTotal + Convert.ToDouble(dataGridView1.Rows[i].Cells["Column6"].Value);
            }
            dgr.Cells["Column6"].Value = double.Parse(numTotal.ToString("F2"));  //数量合计

            dgr.Cells["Column2"].Value = "";
            dgr.Cells["Column4"].Value = "";

            LblHj.Text = CM.Convert(numTotal.ToString(), true);
            if (numTotal < 0)
            {
                LblHj.Text = "负" + LblHj.Text;
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            TotalSum(e);
            TotalRow(true);
        }

        private void TotalSum(DataGridViewCellEventArgs e)
        {
            //MessageBox.Show(e.ColumnIndex.ToString());
            int ci = e.ColumnIndex;
            if (ci == 3 || ci == 4)
            {
                //判断不能为数字
                try { dj = Convert.ToDecimal(dataGridView1[e.ColumnIndex, e.RowIndex].Value); }
                catch { MessageBox.Show("不是数字或形式不正确！"); dataGridView1[e.ColumnIndex, e.RowIndex].Value = ""; return; }
                //如果同一行的数量和单价都不为空，则统计处和价
                try
                {
                    for (int i = 0; i < dataGridView1.RowCount - 1; i++)
                    {
                        if (("" != dataGridView1[4, i].Value) && ("" != dataGridView1[3, i].Value))
                        {
                            dj = Convert.ToDecimal(dataGridView1[4, i].Value);
                            sl = Convert.ToInt64(dataGridView1[3, i].Value);
                            dataGridView1[5, i].Value = dj * sl;
                        }
                    }
                }
                catch { MessageBox.Show("不是数字或形式不正确！"); dataGridView1[e.ColumnIndex, e.RowIndex].Value = ""; return; }
            }
        }

        /// <summary>
        /// 当单击cell时直接进入cell的编辑模式,避免谷歌的bug
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {

            dataGridView1.BeginEdit(true);

        }

        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            //if (dataGridView1.Rows.Count > 0)
            //{
            if (e.Button == MouseButtons.Right)
            {
                this.contextMenuStrip1.Show(this.dataGridView1, new Point(e.X, e.Y));
            }
            //}
        }
        #endregion

        #region 界面初始化
        private void Form1_Load(object sender, EventArgs e)
        {
            this.TxtKdrq.Text = DateTime.Now.ToShortDateString();
            //this.TxtShsj.Text = DateTime.Now.ToShortDateString();
            dataGridView1.Columns[5].ReadOnly = true;
        }
        #endregion


        private void TxtKh_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (0 != dt.Rows.Count)
                {
                    if (dt.Rows[0][1].ToString() == TxtKh.Text) { return; }
                }
                dt = khxxDao.GetKhxxDt(TxtKh.Text.Trim());
                uClistMoreKh.addData(dt);
            }
        }

        private void TxtKdr_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (0 != dt2.Rows.Count)
                {
                    if (dt2.Rows[0][1].ToString() == TxtKdr.Text) { return; }
                }
                dt2 = ygxxDao.GetYgxxDt(TxtKdr.Text.Trim());
                uClistMoreKdr.addData(dt2);
            }
        }

        private void TxtYwy_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (0 != dt1.Rows.Count)
                {
                    if (dt1.Rows[0][1].ToString() == TxtYwy.Text) { return; }
                }
                dt1 = ygxxDao.GetYgxxDt(TxtYwy.Text.Trim());
                uClistMoreYwy.addData(dt1);
            }
        }

        private void TxtShr_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                if (0 != dt3.Rows.Count)
                {
                    if (dt3.Rows[0][1].ToString() == TxtShr.Text) { return; }
                }
                dt3 = ygxxDao.GetYgxxDt(TxtShr.Text.Trim());
                uClistMoreShr.addData(dt3);
            }
        }

        /// <summary>
        /// 因为keyup事件发生在cellleave事件之后，所以里面的currentcell是按回车之后下一个的cell
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
        {
            if (dataGridView1.RowCount == 0) { return; }
            if (dataGridView1.CurrentCell.ColumnIndex == 1)
            {
                dataGridView1.CurrentCell = dataGridView1[0, dataGridView1.CurrentCell.RowIndex];
                if (e.KeyValue == 13)
                {
                    if (dataGridView1.CurrentCell.Value != null && dataGridView1.CurrentCell.Value.ToString().Trim() != "")
                    {
                        //dataGridView1.CurrentCell = dataGridView1[0, dataGridView1.CurrentCell.RowIndex - 1];
                        for (int i = 0; i < dtHp.Rows.Count; i++)
                        {
                            if (dtHp != null && dtHp.Rows[i][0] == dataGridView1.CurrentRow.Cells[0].Value)
                            {
                                return;
                            }
                        }
                        dtHp = hpxxDao.GetHpxxDtByHp_jp(dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString());
                        if (dtHp.Rows.Count != 0)
                        {
                            dataGridView2.DataSource = dtHp;
                            dataGridView2.Show();
                            dataGridView2.Focus();
                            dataGridView2.CurrentCell = dataGridView2[0, 0];
                        }
                        else
                        {
                            MessageBox.Show("未查到相关信息");
                        }
                    }
                    else
                    {
                        MessageBox.Show("请输入简拼来选择一个货品");
                    }
                }
            }
            if (dataGridView1.CurrentCell.ColumnIndex == 5 && e.KeyValue == 13)
            {
                //if (e.KeyValue != 13 ){return;}
                if (dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[5].Value == null || dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[5].Value.ToString().Trim() == "") { return; }
                toolStripMenuItem1_Click(null, null);
                dataGridView1.CurrentCell = dataGridView1[0, dataGridView1.CurrentCell.RowIndex + 1];
            }
        }

        private void dataGridView2_KeyDown(object sender, KeyEventArgs e)
        {
            //MessageBox.Show(dataGridView2[1, dataGridView2.CurrentRow.Index].Value.ToString());
            if (e.KeyCode == Keys.Escape)
            {
                dataGridView2.Visible = false;
                dataGridView1.BeginEdit(false);
                return;
            }
            if (e.KeyCode == Keys.Enter)
            {
                //MessageBox.Show(dataGridView2[1,dataGridView2.CurrentRow.Index].Value.ToString());
                for (int i = 0; i < dataGridView1.RowCount - 1; i++)
                {
                    if (dataGridView1[0, i].Value.ToString().Trim() == dataGridView2[1, dataGridView2.CurrentRow.Index].Value.ToString().Trim())
                    { MessageBox.Show("该货品已在货品单种"); return; }
                }
                dataGridView1.CurrentRow.Cells[0].Value = dataGridView2[1, dataGridView2.CurrentRow.Index].Value;
                dataGridView1.CurrentRow.Cells[4].Value = dataGridView2[2, dataGridView2.CurrentRow.Index].Value;
                dataGridView1.CurrentRow.Cells[2].Value = dataGridView2[3, dataGridView2.CurrentRow.Index].Value;
                dataGridView1.CurrentRow.Cells[1].Value = dataGridView2[4, dataGridView2.CurrentRow.Index].Value;
                dataGridView2.Visible = false;
                dataGridView1.CurrentCell = dataGridView1[3, dataGridView1.CurrentCell.RowIndex];
            }
        }
    }

}
